import { PureComponent } from "react";
import PropTypes from "prop-types"
import MForm from "./MForm";
import { connect } from "dva";
import md5 from "md5"
import { getParmaFromUrl, isNull, goTo, handleUrlParams, handleDataType, filterTemplate, goToPage, calcField, calcArr, isCheckPer, calcPermissionArr, checkPermission, handleDateFunc, backToPrevious } from "../../utils/helper"
import { ActivityIndicator, Modal, Button } from "antd-mobile"
import moment from 'moment';
import MLoading from '../Util/MLoading';
import { saveAs } from 'file-saver'
@connect(({ form, global }, { location }) => {
	let { pathname, search } = location;
	let formDataKey = md5(pathname + search);
	return ({
		fd: form[formDataKey] || {},
		formDataKey,
		queryLoading: global.queryLoading,
		isChangeRefreshing: global.changeRefreshing[formDataKey]
	})
})
export default class Create extends PureComponent {
	constructor(props) {
		super(props);
		this.formRef = "";
		this.modal = null;
		this.enterTime = new Date().getTime();
		this.state = {
			showForm: false,
			paramsMsg: "",
			noLoading: false,
			info: {},
		}
	}
	static propTypes = {
		dispatch: PropTypes.func
	};
	componentWillReceiveProps1(next) {
		let { location: { search: search1 } } = next;
		let { location: { search: search2 } } = this.props;
		if (!_.isEqual(search1, search2)) {// create?_c=a  --> create?_c=b 时页面不会刷新，只是地址栏变化了，这个时候就需要手动处理 重新loadConfig  解决方案改成 修改Main中的key值 key值设为地址栏地址 
			console.log("create-search变化");
			this.enterTime = new Date().getTime();
			this.setState({
				showForm: false,
				paramsMsg: "",
				noLoading: false,
				info: {}
			});
			let { dispatch, formDataKey } = this.props;
			dispatch({
				type: "form/removeState",
				payload: {
					formDataKey
				}
			});
			setTimeout(() => {
				dispatch({
					type: "global/clearModal",
					payload: {

					}
				});
				this.loadConfig()
			})
		}
	}
	componentWillMount() {
		this.loadConfig()
	}
	loadConfig = (prop) => {
		let { isGoTo, refreshing } = prop || {};
		let { location, dispatch, formDataKey } = this.props;
		let { search, pathname, state = {}, hash } = location;
		if (!refreshing) {//下拉刷新时请求config 不清空原来的fd
			dispatch({
				type: "form/setState",
				payload: {
					[formDataKey]: {}
				}
			});
		}
		let params = getParmaFromUrl(search);
		const { _c = "", _copy = "", id = "", oid = "", _view = "", _default = "" } = params;
		if (isNull(_c)) {
			this.setState({
				paramsMsg: "缺少_c参数",
				reloadConfig: {
					reload: true,
					reloadFunc: this.loadConfig
				}
			})
		}
		else if ((_copy == 1 || _view == 1) && isNull(id) && isNull(oid)) {
			this.setState({
				paramsMsg: "缺少id参数",
				reloadConfig: {
					reload: true,
					reloadFunc: this.loadConfig
				}
			})
		}
		else {
			dispatch({
				type: "form/getFC",
				payload: {
					_c: _c,
					formDataKey: formDataKey,
					callback: (config) => {
						console.log("config", config);
						if (config.error) {
							let { code, msg } = config;
							this.setState({
								paramsMsg: <div><span>错误码:{code}</span><br /> <span style={{ color: "#aaa" }}>{msg}</span></div>,
								reloadConfig: {
									reload: true,
									reloadFunc: this.loadConfig
								},
								noLoading: true
							})
						}
						else {
							let { navigate } = config;
							dispatch({
								type: "global/setNavigate",
								payload: {
									navigate,
									config,
									path: pathname + search
								}
							});

							let { api, fields } = config.data_store;
							let paramsDefault = handleUrlParams(fields, params);
							let title = calcField(config.title, paramsDefault);
							dispatch({
								type: "global/setHeaderTitle",
								payload: {
									title,
									path: pathname + search
								}
							});
							if (_copy == 1 || _view == 1 || _default == 1) {
								dispatch({
									type: "form/getInfo",
									payload: {
										apiInfo: api,
										data: params,
										callback: (info) => {
											let timeSub = new Date().getTime() - this.enterTime;
											let timeOut = 0;
											if (timeSub < 300) {
												timeOut = 300 - timeSub;
											}
											setTimeout(() => {
												this.setState({
													info: info,
													paramsDefault,
													showForm: true
												});
												this.setState({
													empty: 1
												});
												if (isGoTo !== false) {
													// goTo(top)
												}
											}, timeOut)
										}
									}
								})
							}
							else {
								let timeSub = new Date().getTime() - this.enterTime;
								let timeOut = 0;
								if (timeSub < 300) {
									timeOut = 300 - timeSub;
								}
								setTimeout(() => {
									this.setState({
										config: config,
										paramsDefault,
										showForm: _copy != 1 && _view != 1 && _default != 1
									});
									this.setState({
										empty: 1
									});
									if (isGoTo !== false) {
										// goTo(top)
									}
								}, timeOut)
							}
						}
					}
				}
			})
		}
	};
	componentDidMount() {

	}
	goUpdate = (e) => {
		let { update_oid } = this.state;
		let { fd: { config }, dispatch } = this.props;
		let update_form_url = config.options.update_form_url;
		let obj = {
			id: update_oid
		};
		update_form_url = filterTemplate(update_form_url, obj);
		if (isNull(filterTemplate(update_form_url, obj))) {
			console.log("没有配置update_form_url");
			return;
		}
		goToPage({ dispatch, config: { url: update_form_url }, isReplace: true })
	};
	formSuccessFunc(result, isShowModal) {
		if (isShowModal !== false) {
			let { fd: { config } } = this.props;
			let { options = {} } = config;
			let { show_go_update, show_continue_add, cancel_label = "取消", close_label = "关闭", success_msg } = options;
			let buttons = [

			];
			if (cancel_label) {
				buttons.push({
					text: cancel_label, onPress: () => {
						console.log('第1个按钮被点击了');
					}
				})
			}
			if (close_label) {
				buttons.push(
					{
						text: close_label, onPress: () => {
							console.log('第2个按钮被点击了');
							backToPrevious();
						}
					}
				)
			}

			if (isNull(show_go_update) || show_go_update != 0) {
				// buttons.push({ text: '去修改', onPress: (e) => this.goUpdate(e) })
			}
			if (isNull(show_continue_add) || show_continue_add != 0) {
				buttons.push({ text: '继续添加', onPress: () => console.log('第0个按钮被点击了') })
			}
			if (isNull(success_msg)) {
				success_msg = "操作成功，请继续操作"
			}
			this.modal = Modal.alert('', <div>{success_msg}</div>, buttons)
		}
	}
	handleSubmit = () => {
		let { fd: { config, formData }, dispatch } = this.props;
		let newFormData = handleDataType(config.data_store.fields, formData);
		delete newFormData.id;
		delete newFormData.oid;
		const { actions } = config;
		let api = actions;
		let payload = {
			data: newFormData,
			apiInfo: api,
			isEditCreate: true,
			formSuccessFunc: this.formSuccessFunc.bind(this)
		};
		dispatch({
			type: "form/query",
			payload
		})
	};
	render() {
		let { showForm, paramsMsg, reloadConfig, paramsDefault, info, noLoading } = this.state;
		if (!showForm) {
			if (noLoading) {
				return (
					<MLoading  {...reloadConfig} />
				)
			}
			else {
				if (isNull(paramsMsg)) {
					return (
						<div className="normal">
							<ActivityIndicator toast text="正在加载" animating={true} />
						</div>
					)
				}
				else {
					return <div className="normal" style={{ textAlign: "center" }}>
						{paramsMsg}
					</div>
				}
			}
		}
		let { formDataKey, fd = {}, dispatch, queryLoading, isModal, isChangeRefreshing } = this.props;

		let { config, formData = {} } = fd;
		const { fields } = config.data_store;
		let allFormData = {
			...paramsDefault,
			...info
		};
		let defaultFormData = {};
		fields.map(item => {
			let itemKey = item.name;
			let defVal = item.default_value;
			let isNumber = item.data_type === "number";
			if (isNull(item.default_value)) {
				defaultFormData[itemKey] = defVal
			}
			else {
				if ((typeof defVal == "string") && defVal.indexOf("_ls.") == 0) {
					let _ls = localStorage;
					let v = eval(defVal);
					if (isNull(v)) {
						v = "";
					}
					defVal = v;
				}
				if (isNumber) {
					if (defVal.toString().indexOf("get") == -1) {
						defaultFormData[itemKey] = Number(defVal)
					}
					else {
						defVal = handleDateFunc(defVal);
						let { is_msec } = item;
						if (isNull(is_msec) || is_msec == 0) {
							defVal = parseInt(defVal / 1000);
						}
						defaultFormData[itemKey] = defVal;
					}
					//时间如果是number  默认到秒 is_msec默认是0
				}
				else if (isNull(item.data_type) || item.data_type === "string") {
					if (defVal.toString().indexOf("get") == -1) {
						defaultFormData[itemKey] = defVal + ""
					}
					else {
						defVal = handleDateFunc(defVal);
						defVal = moment(defVal).format("YYYY-MM-DD HH:mm")
						defaultFormData[itemKey] = defVal;
					}
				}
				else if (item.data_type === "array") {
					defaultFormData[itemKey] = defVal
				}
				else {
					defaultFormData[itemKey] = defVal
				}
			}
			if (allFormData[itemKey] !== undefined) {
				defaultFormData[itemKey] = allFormData[itemKey]
			}
		});
		formData = {
			...defaultFormData,
			...formData
		};
		fields.map(item => {
			let itemKey = item.name;
			let val = defaultFormData[item.field || item.name];
			if (item.data_type === "jsonobject" || item.data_type === "object") {
				//把a:{b:10} 格式转成 "a->b":10格式
				if (!isNull(val)) {
					if (item.data_type == "jsonobject") {
						val = JSON.parse(val);
					}
					function jsonToFormData(str, obj) {
						if (obj instanceof Object) {
							for (let i in obj) {
								jsonToFormData(str + "->" + i, obj[i])
							}
						}
						else {
							defaultFormData[str] = obj
						}
					}
					jsonToFormData(itemKey, val);
				}
				delete defaultFormData[itemKey];
				delete formData[itemKey]
			}
			else if (item.data_type == "hex") {
				let { config } = item;
				let obj = {};
				let len = 0;
				config.map((i, k) => {
					let { name, length, data_type } = i;
					let value = val.substring(len, len + length);
					if (data_type == "number") {
						value = Number(value);
					}
					defaultFormData[name] = value;
					len += length;
				})
				delete defaultFormData[itemKey];
				delete formData[itemKey]
			}
			else if (item.data_type === "jsonarray") {
				//数组字符串转成数组
				if (!isNull(val)) {
					defaultFormData[itemKey] = JSON.parse(val);
				}
			}
			else if (item.data_type === "array") {
				//不做处理
			}
		});
		let isShowFooterButton = true;
		let { widgets } = config;
		let { actions } = widgets;
		let footerBtn = [];
		if (isNull(actions)) {
			isShowFooterButton = false
		}
		else {
			for (let i in actions) {
				let item = { ...actions[i] };
				let { visible, disabled } = item;
				// visible = calcField(visible, formData);
				let _obj = {};
				let { permission_ctrl: _ctrl, permission_code: _code } = item;
				if (isCheckPer(_ctrl, _code) && calcPermissionArr.indexOf(_ctrl) != -1) {
					let per = checkPermission(_code);
					if (item[_ctrl] === undefined) {
						item[_ctrl] = per;
					}
					else {
						_obj[_ctrl] = per
					}
				}
				for (let i in item) {
					let val = item[i];
					if (calcArr.indexOf(i) != -1) {
						let isTrue = calcField(val, formData);
						if (calcPermissionArr.indexOf(i) !== -1) {
							isTrue = isTrue && (_obj[i] !== false);
						}
						item[i] = isTrue;
					}
				}
				if (item.visible === false || item.visible === "0" || item.visible === 0) {
					// console.log("visible为false");
				}
				else {
					// console.log("options",btn[0]);
					disabled = calcField(disabled, formData);
					disabled = disabled === true || disabled === "1" || disabled === 1;
					footerBtn.push({
						...item,
						disabled
					})
				}
			}
		}
		if (footerBtn.length == 0) {
			isShowFooterButton = false
		}
		let normalStyle = {};
		if (!isShowFooterButton) {
			normalStyle = {
				paddingBottom: 0
			}
		}
		if (isModal) {
			normalStyle = {
				...normalStyle,
				paddingTop: 0,
				height: "100%",
				paddingBottom: 0
			}
		}
		let formConfig = {
			isChangeRefreshing,
			loadConfig: this.loadConfig.bind(this),
			formDataKey,
			submitFunc: this.handleSubmit.bind(this),
			formSuccessFunc: this.formSuccessFunc.bind(this),
			config,
			isShowFooterButton,
			footerBtn,
			dispatch,
			defaultFormData,
			formData,
			fd,
			isModal,
			cancelFunc: () => {
				console.log("取消");
			},
			formRef: this.formRef
		};
		return (
			<div className="normal" style={{ ...normalStyle }} >
				{/* <Button onClick={() => {
					// saveAs("https://mc-pic.oss-cn-shanghai.aliyuncs.com/bing.png", "image.jpg")
					saveAs("https://hsjc-m.xuhui.ankaaiot.com/downloadfile?file_path=2020/04/application.pdf&token=nP8pdgE+Wdzh0N2kGYrHEo5D1TF37h7nUS+sH9mZQzBBKM8EMTctTavl/uQJ8cOz8+1oMLwke3QaqWiJjNlGrs4E6qGA05XMgDPtN7cjNBOmBgH5kGRRpi1DmtZ8RIBP", "pdf");
					// saveAs("https://mc-pic.oss-cn-shanghai.aliyuncs.com/test.pdf", "pdf");
					// window.open("https://mc-pic.oss-cn-shanghai.aliyuncs.com/test.docx")
					// window.open("https://mc-pic.oss-cn-shanghai.aliyuncs.com/test.pdf")
					// saveAs("https://mc-pic.oss-cn-shanghai.aliyuncs.com/test.pdf", "pdf");
					// 安卓浏览器可以下载,安卓微信里面自己直接调到浏览器提示下载
					// ios saveAs没反应 window.open 直接打开新页面查看 ,不能下载,下载需要用默认浏览器打开之后手动保存到文件
				}}>
					saveAs
					</Button>
					<Button onClick={()=>{
						window.open("https://hsjc-m.xuhui.ankaaiot.com/downloadfile?file_path=2020/04/application.pdf&token=nP8pdgE+Wdzh0N2kGYrHEo5D1TF37h7nUS+sH9mZQzBBKM8EMTctTavl/uQJ8cOz8+1oMLwke3QaqWiJjNlGrs4E6qGA05XMgDPtN7cjNBOmBgH5kGRRpi1DmtZ8RIBP")
					}}>window.open</Button> */}
				{/* <Button onClick={() => {
						console.log("wx",wx);
						wx.miniProgram.postMessage({ data: { foo: 'bar' } })
						wx.miniProgram.redirectTo({
							// url:'/pages/webviewph/webviewph'
							url:"/pages/webtest/webtest?url=http://192.168.0.103:3333/"
						});
					}}>测试小程序</Button> */}
				{
					queryLoading && <ActivityIndicator toast text="" animating={true} />
				}
				<MForm ref={(e) => this.formRef = e} {...formConfig} location={this.props.location} />
			</div>
		)
	}
	componentWillUnmount() {
		if (this.modal) {
			this.modal.close()
		}
		let { dispatch, formDataKey } = this.props;
		dispatch({
			type: "form/removeState",
			payload: {
				formDataKey
			}
		})
	}
}